import axios from 'axios';
import { Loading, Message } from 'element-ui'
import router from './router'
//响应拦截

let loading;
function startLoading() {
    loading = Loading.service({
        lock: true,
        background: 'rgba(0,0,0,0.7)',
        text: '正在加载中'
    });
}

function endLoading() {
    loading.close();
}

//请求拦截
axios.interceptors.request.use(config => {
    //console.log(config)
    //加载动画
    startLoading();

    // 设置统一请求头
    if(localStorage.eleToken){
        config.headers.authorization = localStorage.eleToken;
    }
    return config

},error=>{
    return Promise.reject(error);
})

axios.interceptors.response.use(response => {
    //结束动画
    endLoading();
    return response

},error=>{
    //错误提醒
    endLoading();
    Message.error(error.response.data);

    //获取请求状态码
    const { status } = error.response;
    if (status == 401) {
        //清除token
        localStorage.removeItem('eleToken');
        Message.error("账号已过期，请重新登录");
        //跳转回登录页
        router.push("./login")
    }

    return Promise.reject(error)
})

export default axios;

